package com.cryptooj.project.judge;

import com.cryptooj.project.common.ErrorCode;
import com.cryptooj.project.exception.BusinessException;
import com.cryptooj.project.judge.codesandbox.CodeSandbox;
import com.cryptooj.project.judge.codesandbox.CodeSandboxFactory;
import com.cryptooj.project.judge.codesandbox.CodeSandboxProxy;
import com.cryptooj.project.judge.codesandbox.model.ExecuteCodeRequest;
import com.cryptooj.project.judge.codesandbox.model.ExecuteCodeResponse;
import com.cryptooj.project.judge.codesandbox.model.JudgeInfo;
import com.cryptooj.project.judge.strategy.JudgeContext;
import com.cryptooj.project.model.dto.question.JudgeCase;
import com.cryptooj.project.model.entity.Question;
import com.cryptooj.project.model.entity.QuestionSubmit;
import com.cryptooj.project.model.enums.QuestionSubmitStatusEnum;
import com.cryptooj.project.service.QuestionService;
import com.cryptooj.project.service.QuestionSubmitService;
import com.cryptooj.project.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import cn.hutool.json.JSONUtil;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService {

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Resource
    private JudgeManager judgeManager;

    // 从配置文件中读取配置信息
    @Value("${codesandbox.type:example}")
    private String type;

    /**
     *  进行判题
     * */
    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if(questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目作答提交记录不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        if(question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目不存在");
        }
        // 若当前题目作答状态不是 ‘等待中’ ，则必定是 ‘ 判题中 ‘ ’成功 ‘ ’失败 ‘
        // 由于不允许用户同时多次提交题目作答，故抛error
        if(questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"正在判题中，请等待当前判题结束");
        }
        // 修改作答状态
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit(); // 为什么不直接在原来的 questionSubmit 对象上修改状态？   -- 避免数据污染：由于questionSubmit对象在后续很可能会被复用，直接修改questionSubmit会导致污染
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目作答状态更新错误");
        }
        // 调用沙箱
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputList = judgeCaseList
                .stream()
                .map(JudgeCase::getInput)
                .collect(Collectors.toList());
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest
                .builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
        List<String> outputList = executeCodeResponse.getOutputList();
        // 根据沙箱中的执行结果，设置题目作答的状态信息
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
        // 修改数据库中的判题结果
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCESS.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目作答状态更新错误");
        }
        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionId);
        return questionSubmitResult;
    }
}
